package com.glory.gloryquickui.view

import android.content.Context
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.glory.gloryquickui.R
import com.glory.gloryquickui.entity.FieldBean
import com.glory.gloryquickui.utils.DateUtils
import com.glory.gloryquickui.viewmodel.QuickUIViewModel
import com.glory.gloryquickui.widget.datepicker.CustomDatePicker

/**
 *日期选择组件
 */
class DateChooseController(context: Context?, val viewModel: QuickUIViewModel) :
    ViewController<FieldBean?>(context) {
    private var tvDateName: TextView? = null
    private var tvDateValue: TextView? = null
    private var flDate: FrameLayout? = null
    private var mDatePicker: CustomDatePicker? = null
    private var selectDate: String = ""
    override fun resLayoutId(): Int {
        return R.layout.layout_date_choose
    }

    override fun onBindView(data: FieldBean?) {
        tvDateName!!.text = data?.config?.label
        tvDateValue!!.hint = data?.placeholder
        initDatePicker(data!!.format)
        flDate!!.setOnClickListener {
            if (selectDate.isNotEmpty()) {
                mDatePicker!!.show(DateUtils.stringToLong(selectDate, data!!.format))
            } else {
                mDatePicker!!.show(
                    DateUtils.stringToLong(
                        DateUtils.getNowStringDate(data!!.format),
                        data!!.format
                    )
                )
            }
        }
    }

    /**
     * 初始化日期选择器
     */
    private fun initDatePicker(format: String) {
        val beginTimestamp = DateUtils.dateToLong(DateUtils.stringToDate("1900-01-01", format))
        val endTimestamp = DateUtils.str2Long(DateUtils.getNowStringDate(format), false)
        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = CustomDatePicker(context, { timestamp ->
            selectDate = DateUtils.longToString(timestamp, format)
            data!!.config.defaultValue = selectDate
            tvDateValue!!.text = selectDate
            val map = viewModel.pageData.value!!.toMutableMap()
            map[data!!.vModel] = selectDate
            viewModel.pageData.value = map
        }, beginTimestamp, endTimestamp)
        mDatePicker!!.setCanShowDay(format.length > 7)
        mDatePicker!!.setCanShowPreciseTime(format.length > 10)
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker!!.setCancelable(true)
        // 不允许循环滚动
        mDatePicker!!.setScrollLoop(false)
        // 不允许滚动动画
        mDatePicker!!.setCanShowAnim(false)
    }

    override fun onCreatedView(view: View?) {
        tvDateName = view?.findViewById(R.id.tvDateName)
        tvDateValue = view?.findViewById(R.id.tvDateValue)
        flDate = view?.findViewById(R.id.flDate)
    }

    override fun masterPart(): View? {
        return tvDateValue
    }
}